from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer

def generate_encrypted_openid(openid):
    """生成加密的openid"""
    #参数1:密钥
    #参数2:有效期,10分钟
    s = TimedJSONWebSignatureSerializer(settings.SECRET_KEY,60*10)
    return s.dumps({'openid':openid}).decode() #加密出来是byte类型 需要转码

def check_openid(encrypted_openid):
    """
    校验openid是否合法(没有篡改,没有过期)
    encrypted_openid:加密后openid
    返回校验通过的openid,如果为空,则表示校验不通过
    """
    s = TimedJSONWebSignatureSerializer(settings.SECRET_KEY,60*10)
    try:
        dict_data = s.loads(encrypted_openid)
    except:
        return None

    return dict_data.get('openid')